import cv2
from flask import *
import os
import time
from datetime import timedelta
from werkzeug.utils import secure_filename
import OCR_detect

# @author: 强睿哲

app = Flask(__name__)




@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template("index.html")


@app.route('/welcome')
def welcome():
    return render_template('welcome.html')


@app.route('/orginal')
def orginal_image():
    return render_template('orginal_image.html')


@app.route('/grey')
def grey_image():
    return render_template('grey_image.html')


@app.route('/screen')
def screen_cnt():
    return render_template('screen_cnt.html')


@app.route('/result')
def result_image():
    return render_template('result_image.html')


@app.route('/txt')
def open_txt():
    return redirect(url_for('static', filename='text_input.txt'))


basedir = os.path.abspath(os.path.dirname(__file__))


@app.route('/upload', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        '''删除文件'''
        # 确保输出文件夹下没有文件
        if os.path.exists("./static/edged.jpg"):
            os.remove("./static/edged.jpg")
        if os.path.exists("./static/image.jpg"):
            os.remove("./static/image.jpg")
        if os.path.exists("./static/ref.jpg"):
            os.remove("./static/ref.jpg")
        if os.path.exists("./static/screenCnt.jpg"):
            os.remove("./static/screenCnt.jpg")

        f = request.files['file']

        user_input = request.form.get("name")

        basepath = os.path.dirname(__file__)  # 当前文件所在路径

        # upload_path = os.path.join(basepath, 'static', secure_filename(f.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
        upload_path = os.path.join(basepath, 'static', 'image.jpg')  #注意：没有的文件夹一定要先创建，不然会提示没有该路径
        f.save(upload_path)

        # 在此处选择读入的图片
        image_read = cv2.imread('./static/image.jpg')
        # 4032 x 3024
        # image_read = cv2.resize(image_read, (500, 300))

        image, orig, ratio = OCR_detect.pre_solve(image_read)
        edged = OCR_detect.pre_edged(image)
        # cv2.imwrite('UI_interface/output_images/image.jpg', image)

        # 展示预处理结果
        # show_pre_solve(image, edged)
        cv2.imwrite('./static/edged.jpg', edged)

        # 展示结果
        screenCnt = OCR_detect.contours_detect(edged)

        # 判断是否扫描到边框，如果没有，额外处理
        if (isinstance(screenCnt, int)):
            OCR_detect.teeeeract_API()

        else:
            # show_contours(image, screenCnt)
            cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)

            cv2.imwrite('./static/screenCnt.jpg', image)

            # 展示结果
            ref = OCR_detect.warp_reshape(orig, ratio, screenCnt)
            # warp_show(orig, ref)
            cv2.imwrite('./static/ref.jpg', ref)
            OCR_detect.teeeeract_API()



        return render_template('upload_ok.html', userinput=user_input, val1=time.time())

    return render_template('upload.html')


app.run()